﻿using CommonModel.Model;
using CommonModel.Util;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Ptllib
{
    public class PtlImp
    {
        //xml配置信息
        static Dictionary<string, SchemaDocument> cfgs = new Dictionary<string, SchemaDocument>();
        static string _ver = "Four_Enviroment_Power_NoHeader";

        public static string getver() { return _ver; }

        //ptlsvr根据matchCfg.xml的配置，把配置信息设置
        public static void setCfg(Dictionary<string, SchemaDocument> cfgs) 
        {
            PtlImp.cfgs = cfgs;
        }

        //解析帧头，判断是否匹配本DLL接口
        public static bool matching(byte[] data)
        {
            //四级环境采集器，第二字节：0x43。四级电源复位器，0x46.
            byte[] flag_1 = data.Skip(16).Take(1).ToArray();
            string flag1 = TransForm.ByteToHexStringBigEndian(flag_1);//转为十六进制字符串

            if (flag1.Equals("43")|| flag1.Equals("46"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /*
         * 解析数据
         * data前15位 IP占4位，端口占2位，时间戳占8位, 协议类别1位 共15位
         */
        public static string convert(byte[] data)
        {
            Dictionary<string, Object> parsedDataDictionary = new Dictionary<string, Object>();
            //四级环境采集器，第二字节：0x43。四级电源复位器，0x46.
            byte[] flag_1 = data.Skip(16).Take(1).ToArray();
            string flag1 = TransForm.ByteToHexStringBigEndian(flag_1);//转为十六进制字符串
            HeaderData header = null;

            if (flag1.Equals("43") || flag1.Equals("46"))
            {
                header = ParseSvr.ByteParseToHead_NoHeader(data);//解析帧头
            }
            else
            {
                Console.WriteLine("第二字节不是43");
                return "";
            }

            if (null == header || header.ErrorFlag.Equals("yes"))
            {
                return null;
            }

            //增加header信息获取厂家为空时的判断
            if (null == header.Vendor || header.Vendor.Equals("技术中心"))
            {
                header.Vendor="0x0000";
            }
            string schemaName = "";
            if (header.Device.Equals("0x00") || header.Device.Equals("0x0703")|| header.Device.Equals("0x0401"))
            {
                schemaName = header.Device + "_" + header.Vendor + "_" + header.MsgType;
            }
            else
            {
                schemaName = header.Device + "_" + header.Vendor + "_" + header.Hardware + "_" + header.Software + "_" + header.MsgType;
            }
                
            SchemaDocument doc = null;
            if (cfgs.ContainsKey(schemaName))
            {
                doc = cfgs[schemaName];// 获取对应的xml解析文件
                parsedDataDictionary = Struct.ByteParseViaStruct(doc, data, header.Bodybegin);
            }
            else
            {
#if DEBUG
                Console.WriteLine("获取解析协议配置失败, 应该获取的协议名称: " + schemaName);
#endif
                return null;
            }

            string jsondata = "";
            //拼接发送的json数据
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            string unix_timestamp = Convert.ToInt64(ts.TotalSeconds).ToString();

            Dictionary<string, object> resultDict = new Dictionary<string, object>();//发送下去的总json数据

            Dictionary<string, string> ptlDict = new Dictionary<string, string>();           
            ptlDict.Add("ptlver", "ptl ver info");
            ptlDict.Add("ts", unix_timestamp);//时间戳
            ptlDict.Add("ptlnode", "");//协议转换节点

            Dictionary<string, string> addDict = new Dictionary<string, string>();          
            addDict.Add("ip", header.Ip);//ip地址
            addDict.Add("port", header.Port.ToString());//端口
            addDict.Add("sid", header.Stationcode);//台站id
            addDict.Add("addr", parsedDataDictionary["Address"].ToString());//四级环境采集器设备地址
            addDict.Add("sn", "");//四级环境采集器文档协议没有，为空
            addDict.Add("paramId", doc.getId());

            resultDict.Add("ptlinfo", ptlDict);
            resultDict.Add("addr", addDict);
            resultDict.Add("datas", parsedDataDictionary);
            jsondata = JsonConvert.SerializeObject(resultDict);
            return jsondata;
        }
    }
}
